﻿using BllFactory;
using ETWebApi2.Models;
using IBLL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Text;
using System.Web;

namespace ETWebApi2.Controllers
{
   [JwtAuthActionFilter]
   [Route("StaffManager")]
    public class StaffManagerController : ApiController
    {
        private ICUser_tbService m_cs = ServiceFactory.CreatService<ICUser_tbService>();
        BaseClass m_bc = new BaseClass();
        /// <summary>
        /// 加载该客户（公司）的所有员工(分页显示)
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页显示的记录数</param>
        /// <param name="ordertype">排序类型 预留 1 --客户姓名排序 2-- 时间排序 0--state状态排序</param>
        /// <returns>每页显示的数据  以及总数</returns>
        [HttpGet]
        public HttpResponseMessage GetByPage(int page,int limit,int ordertype=0,bool isasc=true)
        {
            int count =0;
            JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
            List<CUser_tb> pages = new List<CUser_tb>();
            //按客户姓名排序
            if (ordertype == 1)
                pages = m_cs.GetListByPage(c => c.CompanyId == info.CurentCopmpanyId, c => c.UserName, isasc, page, limit, ref count);

            //按状态排序
            if (ordertype == 0)
                pages = m_cs.GetListByPage(c => c.CompanyId == info.CurentCopmpanyId, c => c.State, isasc, page, limit, ref count);

            //按时间排序
            if (ordertype == 2)
                pages = m_cs.GetListByPage(c => c.CompanyId == info.CurentCopmpanyId, c => c.Time, isasc, page, limit, ref count);

            HttpResponseMessage result = ObjectToJson.toJson(new { status=200,data=new { total = count, rows = pages} });
            return result;
        }

        /// <summary>
        /// 新增员工 
        /// </summary>  
        /// <param name="phone">员工电话</param>
        /// <param name="name">姓名</param>
        /// <param name="remark">备注</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage PostNewstaff(dynamic obj)
        {
            string UserName = obj.UserName.ToString();
            if (m_cs.GetList(c => c.UserName== UserName).FirstOrDefault() != null)
                return ObjectToJson.toJson(new { status = 201, error = "该用户名已存在, 请替换" });
            if (m_cs.GetList(c => ((c.Phone == obj.Phone.ToString() || c.UserName== UserName) && c.State == 1)).FirstOrDefault()!=null)
            {
                return ObjectToJson.toJson(new { status = 201, error = "该用户已存在活动账号" });
            }
            else
            {
                JwtAuthObject info = m_bc.GetInfoByToken(Request.Headers.Authorization.Parameter);
                //随机生成六位数密码   
                Random r = new Random();
                string pwd = r.Next(100000, 999999).ToString();
                CUser_tb newUser = new CUser_tb();
                newUser.CompanyId =Convert.ToInt32(info.CurentCopmpanyId);
                newUser.Phone = obj.Phone.ToString();
                newUser.UserName = obj.UserName.ToString();
                if (obj.Remark == null)
                    newUser.Remark = "";
                else
                    newUser.Remark = obj.Remark.ToString();
                newUser.Role = 0;
                newUser.State = 1;
                newUser.UserPwd = pwd;
                newUser.Time = DateTime.Now;
                newUser.MAC = "";
                if (obj.Phone == null)
                    return ObjectToJson.toJson(new { status = 201, error = "手机号不能为空" });
                else if (obj.Phone.ToString().Length < 11)
                    return ObjectToJson.toJson(new { status = 201, error = "手机号必须为11位" });
                else
                {
                    if (m_cs.Add(newUser))
                    {
                        //短信通知 amzThIYcXZGf 【深圳布易科技】您的用户名是:% P %; 密码是:% P %  
                        //string param = string.Format("&p1={0}&p2={1}", obj.UserName.ToString(), pwd);

                        //string param = string.Format("&p1={0}&p2={1}", newUser.UserName, newUser.UserPwd);
                        //SendMessage.SendSM(obj.Phone.ToString(), "amzThIYcXZGf", param);
                        //return ObjectToJson.toJson(new { status = 200, rel = string.Format("成功添加伙伴！密码已发送到{0}手机上,请注意查收", newUser.Phone) });
                        return ObjectToJson.toJson(new { status = 200, rel = string.Format("成功添加伙伴！密码是:{0}", newUser.UserPwd) });

                    }
                    else
                    {
                        return ObjectToJson.toJson(new { status = 201, error = "添加失败" });
                    }
                }
            }            
        }

        /// <summary>
        /// 修改员工信息   
        /// </summary>   
        /// <param name="upUser">被修改的员工对象</param>
        [HttpPut]
        public HttpResponseMessage PutStaff(CUser_tb upUser)
        {
            if (m_cs.Update(upUser))
                return ObjectToJson.toJson(new { status = 200, rel = true });
            else
                return ObjectToJson.toJson(new { status = 201, error = "信息修改失败!" });
        }
        [HttpPut,Route("checkuser")]
        public HttpResponseMessage CheckEntity(CUser_tb upUser)
        {            
            if (upUser == null)
                return ObjectToJson.toJson(new { status = 201, error = "信息有误" });
            if (!string.IsNullOrEmpty(upUser.Phone))
                if (m_cs.GetList(c => (c.Phone == upUser.Phone && c.Id != upUser.Id)).Count() > 0)
                    return ObjectToJson.toJson(new { status = 201, error = "已存在该手机号" });                
            if (m_cs.GetList(c => c.UserName == upUser.UserName && c.CompanyId == upUser.CompanyId && c.Id != upUser.Id).Count() > 0)
                return ObjectToJson.toJson(new { status = 201, error = "该用户名已存在, 请替换" });
            if(!string.IsNullOrEmpty(upUser.MAC))
                if(m_cs.GetList(c => (c.MAC == upUser.MAC && c.Id != upUser.Id)).Count() > 0)
                    return ObjectToJson.toJson(new { status = 201, error = "已存在该MAC" });
            return ObjectToJson.toJson(new { status = 200, rel = true });
        }
    }
}
